package org.example.java_gobang.api;

import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.example.java_gobang.model.User;
import org.example.java_gobang.model.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class UserAPI {
    @Resource
    private UserMapper userMapper;
    //注册
    @PostMapping("/register")
    @ResponseBody
    public Object register(String username,String password){
        //名字不允许同名
        try{
            User user = new User();
            user.setUsername(username);
            user.setPassword(password);
            userMapper.insert(username,password);
            return user;
            //名字相同时,会注册失败,进行异常处理
        }catch(org.springframework.dao.DuplicateKeyException e){
            User user = new User();
            return user;
        }
    }

    @PostMapping("/login")
    public Object login(String username, String password, HttpServletRequest req){
        User user = userMapper.selectByName(username);
        if(user==null || !user.getPassword().equals(password)){
            System.out.println("登录失败!");
            return new User();
        }
        //登录成功后,将用户信息保存到session中
        HttpSession httpSession = req.getSession(true);//当未创建session时,自动创建
        httpSession.setAttribute("user",user);
        return user;
    }
    @GetMapping("/userInfo")
    @ResponseBody
    public Object getUserInfo(HttpServletRequest req){
        //只要用户登录后,就可以直接从session中获取
        try{
            HttpSession httpSession = req.getSession(false);//此时就不要再让创建新的session,当session不存在时,会抛出空指针异常
            User user = (User)httpSession.getAttribute("user");
            //根据获取到的用户的用户名,从数据库重新查询数据,获取最新的数据
            User user1 = userMapper.selectByName(user.getUsername());
            return user1;
        }catch(NullPointerException e){
            //查找失败,返回空的用户
            return new User();
        }
    }
}
